use std::{path::PathBuf, sync::Arc};

use rand::{random, Rng};
use thunderdome::Index;

use crate::managers::resource_manager::ResourceManagerExt;
use crate::{components::nestable::ItemTrait, core::context::Context};

#[derive(Debug, Clone, PartialEq)]
pub struct ResFile {
    pub path: PathBuf,
    pub file_name: String,
}
impl ResFile {
    pub fn new(path: PathBuf, file_name: String) -> Self {
        Self { path, file_name }
    }

    pub fn get_path(&self) -> String {
        let path_str = self.path.display().to_string();
        let index = path_str.find("assets").unwrap_or_else(|| {
            panic!("Could not find 'assets' in the path: {}", path_str);
        });

        let trimmed_str = &path_str[index + 7..];
        trimmed_str.to_string()
    }
}

#[derive(Hash, Clone, PartialEq, Eq, Debug, Copy)]
pub struct ResItem {
    id: Index,
    index: i32,
}

impl ItemTrait for ResItem {
    fn new(index: Index) -> Self {
        Self {
            id: index,
            index: random(),
        }
    }

    fn get_id(&self) -> Index {
        self.id
    }

    fn get_egui_id(&self) -> egui::Id {
        egui::Id::new(self.index)
    }

    fn get_string(&self, context: Arc<Context>) -> String {
        if let Some(file) = context.resource_manager.get_file(self.id) {
            return file.file_name.clone();
        }

        return String::from("None");
    }
}

impl Default for ResItem {
    fn default() -> Self {
        Self {
            id: Index::DANGLING,
            index: 0,
        }
    }
}
